package com.zoke.support.base;

import android.app.Application;
import android.database.sqlite.SQLiteDatabase;

import com.nostra13.universalimageloader.cache.memory.impl.LruMemoryCache;
import com.nostra13.universalimageloader.core.ImageLoader;
import com.nostra13.universalimageloader.core.ImageLoaderConfiguration;
import com.zoke.support.config.ZokeConfig;
import com.zoke.support.db.JackDb;
import com.zoke.support.db.JackDb.DbUpdateListener;
import com.zoke.support.http.CallBackStores;
import com.zoke.support.utils.MessageHandlerList;
import com.zoke.support.utils.PersistTool;

/**
 * 
 * @author JackWu
 * 
 */
public class BaseApp extends Application {
	// 数据库版本号
	protected static int DBVERSION = 1;
	public static JackDb mAppDb;

	@Override
	public void onCreate() {
		super.onCreate();
		/** 初始化用户偏好设置 **/
		PersistTool.init(getApplicationContext());
		/** 初始化ImageLoader 处理图片 **/
		ImageLoaderConfiguration config = new ImageLoaderConfiguration.Builder(
				getApplicationContext()).writeDebugLogs()
				.memoryCache(new LruMemoryCache(2 * 1024 * 1024)).build();
		ImageLoader.getInstance().init(config);
		/** 初始化数据库 **/
		createDb();
	}

	/** 创建数据库 **/
	public JackDb createDb() {
		if (mAppDb == null)
			mAppDb = JackDb.create(getApplicationContext(), null,
					"zoke_support.db", false, DBVERSION,
					new ZokeDBUpdateListener());
		return mAppDb;
	}

	/** 数据库版本更新监听 **/
	public class ZokeDBUpdateListener implements DbUpdateListener {
		@Override
		public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
			try {
				switch (oldVersion) {
				case 1:
				case 2:
				default:
					break;
				}
			} catch (Exception e) {
			}

		}

	}

	/** 执行双击退出app **/
	public void exitApp() {
		// 让子类去实现，子类不实现会报错
		// 清空回调集
		CallBackStores.getCallback().clearCallbacks();
		// 清楚所有的UI界面（所有继承BaseActivity的界面）
		MessageHandlerList.sendMessage(ZokeConfig.ALL_UI_FINISH);
	}

}
